package com.xyy.controller;

import com.xyy.common.PageResult;
import com.xyy.common.Result;
import com.xyy.dto.DoctorQueryDTO;
import com.xyy.dto.PushDTO;
import com.xyy.dto.PushQueryDTO;
import com.xyy.entity.Admin;
import com.xyy.entity.Doctor;
import com.xyy.vo.PushVO;

import com.xyy.service.AdminService;
import com.xyy.service.DoctorService;
import com.xyy.service.PushService;
import com.xyy.service.FileService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@Validated
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private PushService pushService;

    @Autowired
    private FileService fileService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody Admin admin) {
        try {
            Admin existingAdmin = adminService.login(admin.getUsername(), admin.getPassword());
            
            // 生成JWT token
            String token = jwtUtil.generateAdminToken(existingAdmin.getUsername(), existingAdmin.getId());
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("admin", existingAdmin);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("管理员登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 创建管理员
     */
    @PostMapping("/create")
    public Result<Void> createAdmin(@Valid @RequestBody Admin createDTO) {
        try {
            adminService.createAdmin(createDTO);
            return Result.success();
        } catch (Exception e) {
            log.error("创建管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新管理员信息
     */
    @PutMapping("/update")
    public Result<Void> updateAdmin(@Valid @RequestBody Admin admin) {
        try {
            adminService.updateAdmin(admin);
            return Result.success();
        } catch (Exception e) {
            log.error("更新管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 软删除管理员
     */
    @DeleteMapping("/delete/{adminId}")
    public Result<Void> deleteAdmin(@PathVariable Long adminId) {
        try {
            adminService.deleteAdmin(adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量软删除管理员
     */
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDeleteAdmin(@RequestBody List<Long> adminIds) {
        try {
            adminService.batchDeleteAdmin(adminIds);
            return Result.success();
        } catch (Exception e) {
            log.error("批量删除管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询管理员
     */
    @PostMapping("/page")
    public Result<PageResult<Admin>> pageQuery(@RequestBody Admin admin,
                                              @RequestParam(defaultValue = "1") Integer current,
                                              @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageResult<Admin> result = adminService.pageQuery(admin, current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询管理员详情
     */
    @GetMapping("/detail/{adminId}")
    public Result<Admin> getAdminDetail(@PathVariable Long adminId) {
        try {
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return Result.error("管理员不存在");
            }
            return Result.success(admin);
        } catch (Exception e) {
            log.error("查询管理员详情失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取管理员列表
     */
    @GetMapping("/list")
    public Result<List<Admin>> getAdminList() {
        try {
            List<Admin> admins = adminService.getAllAdmins();
            return Result.success(admins);
        } catch (Exception e) {
            log.error("获取管理员列表失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 按医院名称查询医生（普通管理员只能查看自己医院的医生）
     */
    @PostMapping("/doctors")
    public Result<PageResult<Doctor>> getDoctorsByHospital(@RequestBody DoctorQueryDTO queryDTO,
                                                          @RequestParam(defaultValue = "1") Integer current,
                                                          @RequestParam(defaultValue = "10") Integer size,
                                                          HttpServletRequest request) {
        try {
            // 从request属性中获取管理员ID（JWT拦截器已验证并设置）
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            // 获取管理员信息
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return Result.error("管理员不存在");
            }
            
            // 如果是普通管理员，只能查看自己医院的医生
            if (admin.getLevel() == 1) {
                queryDTO.setHospitalName(admin.getRealName());
            }
            
            // 查询医生
            PageResult<Doctor> result = doctorService.pageQueryForAdmin(queryDTO, current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询医生失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    // ==================== 推文管理接口 ====================

    /**
     * 创建推文
     */
    @PostMapping("/push/create")
    public Result<Void> createPush(@Valid @RequestBody PushDTO pushDTO, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            pushService.createPush(pushDTO, adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("创建推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新推文
     */
    @PutMapping("/push/update")
    public Result<Void> updatePush(@Valid @RequestBody PushDTO pushDTO, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            pushService.updatePush(pushDTO, adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("更新推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除推文
     */
    @DeleteMapping("/push/delete/{pushId}")
    public Result<Void> deletePush(@PathVariable Long pushId, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            pushService.deletePush(pushId, adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量删除推文
     */
    @DeleteMapping("/push/batch-delete")
    public Result<Void> batchDeletePush(@RequestBody List<Long> pushIds, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            pushService.batchDeletePush(pushIds, adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("批量删除推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 发布推文
     */
    @PostMapping("/push/{pushId}/publish")
    public Result<Void> publishPush(@PathVariable Long pushId, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            pushService.publishPush(pushId, adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("发布推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 撤回推文
     */
    @PostMapping("/push/{pushId}/withdraw")
    public Result<Void> withdrawPush(@PathVariable Long pushId, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            pushService.withdrawPush(pushId, adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("撤回推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询推文
     */
    @PostMapping("/push/page")
    public Result<PageResult<PushVO>> pageQueryPush(@RequestBody PushQueryDTO queryDTO,
                                                   @RequestParam(defaultValue = "1") Integer current,
                                                   @RequestParam(defaultValue = "10") Integer size,
                                                   HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            // 所有管理员都只能查看自己发布的推文（取消超级管理员特权）
            queryDTO.setPublisherId(adminId);
            
            PageResult<PushVO> result = pushService.pageQuery(queryDTO, current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询推文失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询推文详情
     */
    @GetMapping("/push/detail/{pushId}")
    public Result<PushVO> getPushDetail(@PathVariable Long pushId, HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            PushVO pushVO = pushService.getPushById(pushId);
            if (pushVO == null) {
                return Result.error("推文不存在");
            }
            
            // 所有管理员都只能查看自己发布的推文（取消超级管理员特权）
            if (!pushVO.getPublisherId().equals(adminId)) {
                return Result.error("无权限查看此推文");
            }
            
            return Result.success(pushVO);
        } catch (Exception e) {
            log.error("查询推文详情失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取推文列表
     */
    @GetMapping("/push/list")
    public Result<List<PushVO>> getPushList(HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            // 所有管理员都只能查看自己发布的推文（取消超级管理员特权）
            PushQueryDTO queryDTO = new PushQueryDTO();
            queryDTO.setPublisherId(adminId);
            PageResult<PushVO> result = pushService.pageQuery(queryDTO, 1, 1000);
            return Result.success(result.getRecords());
        } catch (Exception e) {
            log.error("获取推文列表失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传推文封面
     */
    @PostMapping("/push/uploadCover")
    public Result<Map<String, String>> uploadPushCover(@RequestParam("cover") MultipartFile file,
                                                      HttpServletRequest request) {
        try {
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageFile(originalFilename)) {
                return Result.error("只支持jpg, jpeg, png, gif, bmp格式的图片");
            }
            
            // 验证文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }
            
            // 上传封面并返回文件路径
            String coverPath = fileService.uploadCover(file);
            
            // 构建完整的封面URL
            String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String fullCoverUrl = serverUrl + "/picture/" + coverPath;
            
            Map<String, String> result = new HashMap<>();
            result.put("coverUrl", fullCoverUrl);
            
            return Result.success("封面上传成功", result);
        } catch (Exception e) {
            log.error("推文封面上传失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }


    /**
     * 检查文件是否为有效的图片文件
     */
    private boolean isValidImageFile(String filename) {
        if (filename == null) {
            return false;
        }
        String lowerCaseFilename = filename.toLowerCase();
        return lowerCaseFilename.endsWith(".jpg") || 
               lowerCaseFilename.endsWith(".jpeg") || 
               lowerCaseFilename.endsWith(".png") || 
               lowerCaseFilename.endsWith(".gif") || 
               lowerCaseFilename.endsWith(".bmp");
    }

} 